package com.example.demo.api;

import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import com.example.demo.utils.ParamsCheck;
import com.example.demo.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/userApi")
@CrossOrigin
public class UserApi {

    @Autowired
    private UserService userSer;

    @RequestMapping("login")
    public Result login(String name, String pwd, HttpServletRequest request) {
        log.info("login");
        ParamsCheck.checkNullOrEmpty(name, "name");
        ParamsCheck.checkNullOrEmpty(pwd, "pwd");
        UserInfo ui = userSer.getUserByName(name);
        if (ui != null && ui.getPassword().equals(pwd)) {
            HttpSession session = request.getSession();
            session.setAttribute("userId", ui.getId());
            return Result.msg("登录成功");
        } else {
            return Result.msg("用户名或密码错误!");
        }
    }

    @PostMapping("addUser")
    public Result addUser(String name, String pwd, Integer age) {
        log.info("add user");
        ParamsCheck.checkNullOrEmpty(name, "name");
        ParamsCheck.checkNullOrEmpty(age, "age");
        ParamsCheck.checkNullOrEmpty(pwd, "pwd");
        UserInfo ui = userSer.getUserByName(name);
        if (ui != null) {
            return Result.error("User " + name + " already exists");
        }
        userSer.addUser(name, age, pwd);
        return Result.ok();
    }

    @GetMapping("getUsers")
    public Result getUsers() {
        return Result.ok(userSer.getAllUsers());
    }

}
